<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24" :xs="24">
        <el-card>
          <div class="filter-container">

            <el-button class="filter-item" icon="el-icon-plus" style="margin-left:40px" type="primary"
                       @click="createTask">
              新建计划任务
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="equipTable"
              v-loading="listLoading"
              :cell-style="{padding:0+'px'}"
              :data="list"
              :row-style="{height:40+'px'}"
              border
              fit
              height="700"
              highlight-current-row
              stripe
              style="width: 100%;"
            >
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column align="center" label="名称" width="80">
                <template slot-scope="{row}">
                  <span>{{ row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="指令">
                <template slot-scope="{row}">
                  <span>{{ formatCronType(row) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="时间表达式">
                <template slot-scope="{row}">
                  <span>{{ row.cron_spec }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="应用区域">
                <template slot-scope="{row}">
                  <span>{{ row.address }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="状态">
                <template slot-scope="{row}">
                  <el-tag
                    :type="formatStatusColor(row.status)"
                    effect="dark">
                    {{ formatStatus(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" label="上次执行时间" width="200">
                <template slot-scope="{row}">
                  <span>{{ formatDate(row.run_time) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" class-name="small-padding fixed-width" label="操作"
                               width="120">
                <template slot-scope="{row,$index}">
                  <el-dropdown @command="handleCommand">
                    <el-button v-if="checkPermission('编辑任务')" size="small" type="primary" @click="updateTask(row)">
                      编辑<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        v-if="checkPermission('激活任务') && row.status==0"
                        :command="{'cmd':'active','row': row}"
                        icon="el-icon-check">
                        激活
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="checkPermission('暂停任务') && row.status==1"
                        :command="{'cmd':'disable','row': row}"
                        icon="el-icon-video-pause">
                        暂停
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="checkPermission('执行任务') && row.status==1"
                        :command="{'cmd':'run','row': row}"
                        icon="el-icon-video-play">
                        执行
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="checkPermission('删除任务') && row.status==0"
                        :command="{'cmd':'delete','row': row}"
                        icon="el-icon-delete">
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getTaskList"/>
            <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
                       custom-class="window-small-width">
              <el-form ref="dataForm" :model="temp" :rules="rules" label-position="right" label-width="80px"
              >
                <el-form-item label="所属区域" prop="area">
                  <area-selector ref="areaSelector" :area-type="areaType" :areas="treeAreas" :checkStrictly="false"
                                 :value="temp.area_code"
                                 v-on:selectArea="onSelectArea"></area-selector>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                  <el-input v-model="temp.name" style="width:220px "/>
                </el-form-item>
                <el-form-item label="定时规则" prop="cron_spec">
                  <el-select v-model="temp.cron_type" placeholder="请选择" style="margin-top: 1px">
                    <el-option
                      v-for="item in [{'name':'每时',value:1},{'name':'每天',value:2},{'name':'每周',value:3},{'name':'每月',value:4},{'name':'每年',value:5}]"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value">
                    </el-option>
                  </el-select>
                  <el-row :gutter="24">
                    <el-col :span="6">
                      <el-select v-if="temp.cron_type==5" v-model="temp.month" placeholder="请选择"
                                 style="margin-top: 5px">
                        <el-option
                          v-for="item in 12"
                          :key="item"
                          :label="item+' 月'"
                          :value="item">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="7">
                      <el-select v-if="temp.cron_type==3" v-model="temp.week" placeholder="请选择" style="margin-top: 5px">
                        <el-option
                          v-for="w in [{name:'周一',value:2},{name:'周二',value:3},{name:'周三',value:4},{name:'周四',value:5},{name:'周五',value:6},{name:'周六',value:7},{name:'周日',value:1}]"
                          :key="w.value"
                          :label="w.name"
                          :value="w.value">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="6">
                      <el-select v-if="temp.cron_type>2 && temp.cron_type!=3" v-model="temp.day" placeholder="请选择"
                                 style="margin-top: 5px">
                        <el-option
                          v-for="item in 31"
                          :key="item"
                          :label="item+' 日'"
                          :value="item">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="6">
                      <el-select v-if="temp.cron_type>1" v-model="temp.hour" placeholder="请选择" style="margin-top: 5px">
                        <el-option
                          v-for="item in 24"
                          :key="item"
                          :label="item-1+' 时'"
                          :value="item-1">
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="6">
                      <el-select v-model="temp.minute" placeholder="请选择" style="margin-top: 5px">
                        <el-option
                          v-for="item in 60"
                          :key="item"
                          :label="item-1+' 分'"
                          :value="item-1">
                        </el-option>
                      </el-select>
                    </el-col>
                  </el-row>
                  <el-input
                    v-model="cronSpec"
                    :disabled="true"
                    style="margin-top: 5px;width: 220px">
                  </el-input>
                </el-form-item>
                <el-form-item label="指令类型" label-width="80px" prop="command">
                  <el-select v-model="temp.command" placeholder="请选择指令" style="margin-top: 5px">
                    <el-option
                      v-for="item in commands"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="temp.command === 4" label="上传频率" label-width="80px" prop="rate">
                  <el-select v-model="temp.params.rate" placeholder="请选择">
                    <el-option
                      v-for="item in 31"
                      :key="item"
                      :label="item+' 天'"
                      :value="item">
                    </el-option>
                  </el-select>
                  <el-time-select
                    v-model="temp.params.time"
                    :picker-options="{
                      start: '00:00',
                      step: '00:10',
                      end: '24:00'
                      }"
                    placeholder="选择时间"
                    style="margin-top: 5px">
                  </el-time-select>
                </el-form-item>
                <el-form-item v-if="temp.command === 5" label="洗阀" label-width="80px" prop="rate">
                  <el-select v-model="temp.params.zerocheck" placeholder="请选择">
                    <el-option
                      v-for="item in [{name:'开',value:1}, {name:'关',value:0}]"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="temp.command === 6" label="正向水量" prop="model">
                  <el-input v-model.number="temp.params.positive_volume" style="width:220px " type="number"/>
                </el-form-item>
                <el-form-item v-if="temp.command === 6" label="反向水量" prop="model">
                  <el-input v-model.number="temp.params.reverse_volume" style="width:220px " type="number"/>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="submitLoading" type="primary"
                           @click="dialogStatus == 'create' ? handleCreate():handleUpdate()">
                  确认
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination';
import {checkPermission} from "@/utils/permission";
import jsUtils from 'jutils-src'
import {activeTask, createTask, deleteTask, disableTask, getTaskList, runTask, updateTask} from "@/api/task";
import AreaSelector from '@/components/area/AreaSelector'
import {getAreaTree} from "@/api/area";

const defaultTask = {
  name: '',
  cron_spec: '',
  command: '',
  area_code: '',
  cron_type: '',
  month: 1,
  week: 1,
  day: 1,
  hour: 0,
  minute: 0,
  params: {
    zerocheck: 0,
    upvalveopen: 0,
    calibration: 0,
    rate: 1,
    time: '18:30',
    minite: '',
    hour: '',
    positive_volume: 0,
    reverse_volume: 0
  },
  remark: ''
}

export default {
  name: 'logs',
  components: {AreaSelector, Pagination},
  data() {
    return {
      tableKey: 0,
      dialogFormVisible: false,
      deviceLogs: [],
      listLoading: true,
      submitLoading: false,
      list: [],
      areaType: 2,
      treeAreas: [],
      dialogStatus: 'create',
      textMap: {
        update: '编辑计划任务',
        create: '新建计划任务'
      },
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      commands: [{id: 1, name: '时间校准'}, {id: 2, name: '开阀'}, {id: 3, name: '关阀'}, {id: 4, name: '调整上传频率'}, {
        id: 5,
        name: '洗阀'
      }, {id: 6, name: '设置水量'}],
      temp: {},
      rules: {},
    }
  },
  created() {
    this.temp = defaultTask
    this.getTaskList()
    this.getAreaTree()
  },
  computed: {
    cronSpec() {
      let tmp = ["*", "*", "*", "*", "?"]  //Seconds Minutes Hours DayOfMonth Month DayOfWeek
      switch (this.temp.cron_type) {
        case 1: //每时
          tmp[0] = this.temp.minute
          break
        case 2://每天
          tmp[0] = this.temp.minute
          tmp[1] = this.temp.hour
          break
        case 3: //每周
          tmp[0] = this.temp.minute
          tmp[1] = this.temp.hour
          tmp[4] = this.temp.week
          break
        case 4: //每月
          tmp[0] = this.temp.minute
          tmp[1] = this.temp.hour
          tmp[2] = this.temp.day
          break
        case 5:
          tmp[0] = this.temp.minute
          tmp[1] = this.temp.hour
          tmp[2] = this.temp.day
          tmp[3] = this.temp.month
          break
      }
      return tmp.join(" ")
    }
  },
  methods: {
    checkPermission,
    handleCommand(command) {
      const {cmd, row} = command
      switch (cmd) {
        case 'edit':
          this.updateTask(row)
          break
        case 'delete':
          this.handleDelete(row)
          break
        case 'active':
          this.handleActive(row)
          break
        case 'disable':
          this.handleDisable(row)
          break
        case 'run':
          this.handleRun(row)
          break
      }
    },
    getAreaTree() {
      getAreaTree({type: 2}).then(response => {
        this.treeAreas = response.data
      })
    },
    onSelectArea(data) {
      if (data != '') {
        this.temp.area_code = data.value
      } else {
        this.temp.area_code = ''
      }
    },
    getTaskList() {
      this.listLoading = true
      let queryData = Object.assign({}, this.listQuery)
      getTaskList(queryData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    createTask() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleCreate() {
      this.submitLoading = true
      const data = Object.assign({}, this.temp)
      data.cron_spec = this.cronSpec
      data.params.rate = parseInt(data.params.rate)
      if (data.cmd === 4) {
        let t = data.params.time.split(':')
        if (t.length < 2) {
          this.$message.error('上传时间设置错误')
          return
        }
        data.params.hour = t[0]
        data.params.minite = t[1]
      }
      createTask(data).then(resp => {
        if (resp.code === 20000) {
          this.getTaskList()
          this.$message.success("计划任务添加成功")
        } else {
          this.$message.error(resp.message)
        }
        setTimeout(() => {
          this.submitLoading = false
        }, 1.5 * 1000)
      })
    },
    updateTask(row) {
      this.resetTemp()
      this.temp = row
      this.temp.params = row.c_params
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    handleUpdate() {
      this.submitLoading = true
      let data = Object.assign({}, this.temp)
      data.command = data.command === 3 ? 2 : data.command
      updateTask(data).then(resp => {
        if (resp.code == 20000) {
          this.$message.success("计划任务修改成功")
        } else {
          this.$message.error(resp.message)
        }
        setTimeout(() => {
          this.submitLoading = false
        }, 1.5 * 1000)
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该计划任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTask({task_id: row.id}).then(response => {
          if (response.code == 20000) {
            this.$message.success("成功删除")
            this.getTaskList()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },
    handleRun(row) {
      this.$confirm('立即执行' + row.name + '计划任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        runTask({task_id: row.id}).then(response => {
          if (response.code == 20000) {
            this.$message.success("已执行")
            this.getTaskList()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },
    handleDisable(row) {
      this.$confirm('立即暂停' + row.name + '计划任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disableTask({task_id: row.id}).then(response => {
          if (response.code == 20000) {
            row.status = 0
            this.$message.success("已暂停")
            this.getTaskList()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },
    handleActive(row) {
      this.$confirm('立即激活' + row.name + '计划任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        activeTask({task_id: row.id}).then(response => {
          if (response.code == 20000) {
            row.status = 1
            this.$message.success("已激活")
            this.getTaskList()
          } else {
            this.$message.error(response.message)
          }
        })
      })
    },
    formatDate(dateStr) {
      const d = new Date(dateStr)
      if (d.getMilliseconds() == 0) {
        return '-'
      }
      return jsUtils.formatDate(d, 'YYYY-MM-DD HH:ii:ss')
    },
    resetTemp() {
      this.temp = Object.assign({}, defaultTask)
    },
    formatStatus(status) {
      switch (status) {
        case 0:
          return '未激活'
        case 1:
          return '已激活'
        case 2:
          return '执行中'
      }
    },
    formatStatusColor(status) {
      switch (status) {
        case 0:
          return 'danger'
        case 1:
          return 'success'
        case 2:
          return 'warning'
      }
    },
    formatCronType(row) {
      switch (row.command) {
        case 1:
          return '时间校准'
        case 2:
          return '开阀'
        case 3:
          return '关阀'
        case 4:
          return '调整上传频率'
        case 5:
          return '洗阀'
        case 6:
          return '设置水量'
      }
    }
  }
}
</script>
